#include "mainwidget.h"

MainWidget::MainWidget(QWidget *parent)
    : QWidget(parent)
{


    this->con=MyControl::getInstance();
    this->initUI();
    this->resize(300,900);


}


void MainWidget::HaveLogin(int x)
{
    if(!isLogin)
    {
        int res=QMessageBox::question(this, "未登录", "请先登录",QMessageBox::Yes | QMessageBox::No);
        if(res==QMessageBox::Yes)
        {
//            this->isLogin=true;
            emit TologinWidget(x);



            if(this->decode->getIsStop()==false&&this->encode->getIsStop()==false)
            {
                this->decode->setIsStop(true);
                this->encode->setIsStop(true);
            }
        }
    }
    else {
        if(x!=0)
        if(this->decode->getIsStop()==false&&this->encode->getIsStop()==false)
        {
            this->decode->setIsStop(true);
            this->encode->setIsStop(true);
        }
    }
}

DecodeVideo *MainWidget::getDecode() const
{
    return decode;
}

void MainWidget::setDecode(DecodeVideo *value)
{
    decode = value;
}

EncodeVideo *MainWidget::getEncode() const
{
    return encode;
}

void MainWidget::setEncode(EncodeVideo *value)
{
    encode = value;
}

QPushButton *MainWidget::getLogIn_button()
{
    return logIn_button;
}

void MainWidget::setLogIn_button(QPushButton *value)
{
    logIn_button = value;
}


MainWidget::~MainWidget()
{
}

void MainWidget::initUI()
{
    this->isLogin=false;

    this->title=new QLabel("执法记录仪",this);
    this->screen=new QLabel("实时录像",this);
    this->image= new QPixmap(/*"../image/result.png"*/);
    this->screen->setPixmap(*image);
    this->takePicture_button=new QPushButton("现场拍照",this);
    this->playback_button=new QPushButton("录像回放",this);
    this->pictrue_button=new QPushButton("现场图片",this);
    this->log_button=new QPushButton("查看日志",this);
    this->transcode_button=new QPushButton("录像转码",this);
    this->set_button=new QPushButton("系统设置",this);
    this->logIn_button=new QPushButton("登录",this);


    this->layout_H1=new QHBoxLayout();
    this->layout_H2=new QHBoxLayout();
    this->layout_H3=new QHBoxLayout();
    this->layout_H4=new QHBoxLayout();
    this->layout_H5=new QHBoxLayout();

    this->layout_V=new QVBoxLayout();


    //中间录像的显示设置
    this->screen->setMinimumSize(600,600);  // 宽x高，根据布局调整
    this->screen->setMaximumSize(600,600);
    this->screen->setAlignment(Qt::AlignCenter);  // 文本居中
    this->screen->setStyleSheet("QLabel {"
                            "border: 2px solid black;"  // 2 像素宽的黑色实线边框
                            "border-radius: 5px;"      // 边框圆角半径为 5 像素
                            "padding: 10px;"           // 内边距为 10 像素
                            "}");


    //布局设置
    layout_V->setSpacing(20);  // 调整垂直间距为 10，可根据实际情况修改
    layout_V->setContentsMargins(80, 20, 80, 100);  // 设置整体边距





    QSizePolicy log_buttonPolicy = log_button->sizePolicy();
    log_buttonPolicy.setHorizontalStretch(1); // 减小下拉框的水平拉伸因子
    log_button->setSizePolicy(log_buttonPolicy);
    log_button->setMaximumWidth(150); // 设置下拉框的最大宽度

    //字体设置
    QFont font;
    font.setPixelSize(30);
    font.setBold(true);//字体加粗

    this->title->setFont(font);
    this->screen->setFont(font);
     this->takePicture_button->setFont(font);
    this->playback_button->setFont(font);
    this->pictrue_button->setFont(font);
    this->log_button->setFont(font);
    this->transcode_button->setFont(font);
    this->set_button->setFont(font);
    this->logIn_button->setFont(font);


    //按钮样式表
    QString buttonStyle = "QPushButton {"
                          "  background-color: white;"  // 正常状态背景颜色为白色
                          "  color: black;"               // 文字颜色为黑色
                          "  border: none;"               // 无边框
                          "  border-radius: 5px;"         // 圆角效果，半径为 5px
                          "  padding: 10px 20px;"         // 内边距，上下 10px，左右 20px
                          "  font-size: 30px;"            // 字体大小为 16px
                          "  font-weight: bold;"          // 字体加粗
                          "}"
                          "QPushButton:hover {"
                          "  background-color: #0056b3;"  // 鼠标悬停时背景颜色变深
                          "}"
                          "QPushButton:pressed {"
                          "  background-color: #003d80;"  // 鼠标点击时背景颜色更深
                          "}";




//    QSize buttonSize(50, 50); // 你可以根据需要调整按钮的大小
//    takePicture_button->setMinimumSize(buttonSize);
//    playback_button->setMinimumSize(buttonSize);
//    pictrue_button->setMinimumSize(buttonSize);
//    log_button->setMinimumSize(buttonSize);
//    transcode_button->setMinimumSize(buttonSize);
//    set_button->setMinimumSize(buttonSize);
//    logIn_button->setMinimumSize(buttonSize);


    int buttonWidth = 200; // 可根据需求调整按钮宽度
    takePicture_button->setFixedWidth(buttonWidth);
    playback_button->setFixedWidth(buttonWidth);
    pictrue_button->setFixedWidth(buttonWidth);
    log_button->setFixedWidth(buttonWidth);
    transcode_button->setFixedWidth(buttonWidth);
    set_button->setFixedWidth(buttonWidth);
    logIn_button->setFixedWidth(buttonWidth);


    takePicture_button->setStyleSheet(buttonStyle);
    playback_button->setStyleSheet(buttonStyle);
    pictrue_button->setStyleSheet(buttonStyle);
    log_button->setStyleSheet(buttonStyle);
    transcode_button->setStyleSheet(buttonStyle);
    set_button->setStyleSheet(buttonStyle);
    logIn_button->setStyleSheet(buttonStyle);





    this->layout_H1->addWidget(title);
    this->layout_H1->setAlignment(Qt::AlignCenter);  // 标题居中
    this->layout_H2->addWidget(screen);
    this->layout_H3->addWidget(takePicture_button);
    this->layout_H3->addWidget(playback_button);
    this->layout_H3->addWidget(pictrue_button);
    this->layout_H4->addWidget(log_button);
    this->layout_H5->addWidget(transcode_button);
    this->layout_H5->addWidget(set_button);
    this->layout_H5->addWidget(logIn_button);

    this->layout_V->addLayout(layout_H1);
    this->layout_V->addLayout(layout_H2);
    this->layout_V->addLayout(layout_H3);
    this->layout_V->addLayout(layout_H4);
    this->layout_V->addLayout(layout_H5);
    this->setLayout(layout_V);


    //视频录像
    this->decode=new DecodeVideo();

//    connect(this->decode,&DecodeVideo::sendMaxTime,this,&MainWidget::TimeturnMax);
    this->encode=new EncodeVideo();
     connect(this->encode,&EncodeVideo::sendWriteDateBase,this,&MainWidget::WriteDateBaseVide);
    connect(this->encode,&EncodeVideo::sendTimeMax,this->decode,&DecodeVideo::SetXToBegin);

    this->decode->filePrepare("");

    this->encode->setWight(this->decode->getWight());
    this->encode->setHight(this->decode->getHight());


    this->encode->initEncode();
    //connect(this->decode,&DecodeVideo::sendWightHight,this->encode,&EncodeVideo::reciverWightHight);
    this->decode->setSpeed(15);
    this->decode->start();


    //this->encode->initEncode();


    qDebug()<<"encode wight"<<encode->getWight()<<"encode hight"<<encode->getHight();
    this->encode->start();



    connect(this->decode,&DecodeVideo::sendImage,this,&MainWidget::VideoCording);
    connect(this->decode,&DecodeVideo::sendYUV,this->encode,&EncodeVideo::reciverYUV);
    connect(this->decode,&DecodeVideo::sendclose,this->encode,&EncodeVideo::CloseFile);
    connect(this,&MainWidget::CloseDecode,this->decode,&DecodeVideo::stopDecode);
    connect(this,&MainWidget::CloseEncode,this->encode,&EncodeVideo::reciverExit);
    //现成图片
    connect(this->pictrue_button,&QPushButton::clicked,this,&MainWidget::Clickpictrue_button);
    //录像回放
    connect(this->playback_button,&QPushButton::clicked,this,&MainWidget::Clickplayback_button);
    //现场拍照
    connect(this->takePicture_button,&QPushButton::clicked,this,&MainWidget::ClicktakePicture_button);
    //查看日志
    connect(this->log_button,&QPushButton::clicked,this,&MainWidget::Clicklog_button);
    //录像转码
    connect(this->transcode_button,&QPushButton::clicked,this,&MainWidget::Clicktranscode_button);
    //登录
    connect(this->logIn_button,&QPushButton::clicked,this,&MainWidget::ClicklogIn_button);
    //系统设置
    connect(set_button,&QPushButton::clicked,this,&MainWidget::ClicksetWidget);



}

bool MainWidget::getIsLogin() const
{
    return isLogin;
}

void MainWidget::setIsLogin(bool value)
{
    isLogin = value;
}

void MainWidget::paintEvent(QPaintEvent *event)
{
    if(image)
    {
        this->screen->setPixmap(*image);
    }
}

void MainWidget::VideoCording(QImage img)
{
    if(!img.isNull())
    {
        *(this->image)=QPixmap::fromImage(img);
    }
}


void MainWidget::closeEvent(QCloseEvent *event)
{
    int ret = QMessageBox::question(this, "确认关闭", "你确定要关闭窗口吗？这将结束视频录制并写入尾帧。",
                                        QMessageBox::Yes | QMessageBox::No);
    if (ret == QMessageBox::Yes)
       {
           // 调用EncodeVideo类的方法写入尾帧
           if (encode)
           {
              //发送信号给编码线程让它发送结束标志
               this->encode->CloseFile();//主动让他写尾帧，不然这里会因为程序终止而写不到尾帧
               emit CloseDecode();//发送信号让解码线程退出事件循环
               emit CloseEncode();
           }
           if(this->isLogin)//登录就就写进去，不登陆就不写入数据库
           {

               this->model=this->con->getModel("video_file");
               QString sql=QString("insert into video_files (user_id,video_path,video_name,duration,video_img_path) VALUES (%1,'%2','%3','%4','%5');")
                       .arg(id)
                       .arg(this->getEncode()->getVideooutPath().toStdString().c_str())
                       .arg(this->getEncode()->getVideooutName().toStdString().c_str())
                       .arg(qCeil((qreal)this->getDecode()->getX()))
                       .arg(this->getDecode()->getVideo_img_path().toStdString().c_str());
               qDebug()<<sql;

               this->model->insetVideoInfo((char *)sql.toStdString().c_str());
    //         这里把拍摄的视频和照片导入到数据库中
           }

           // 允许关闭窗口
           event->accept();
       }
       else
       {
           // 阻止窗口关闭
           event->ignore();
       }
}

//enum
//{
//    takePictrueWidget,//0
//    playbackWidget,//1
//    pictrueWidget,//2
//    logWidget,//3
//    transcodeWidget,//4
//    setWidget,//5
//    logInWidget//6
//};


void MainWidget::ClicksetWidget()
{
   HaveLogin(5);
   if(this->isLogin)
   emit TosetWidget();

}


void MainWidget::ClicktakePicture_button()
{
    HaveLogin(0);
    if(isLogin)
    {
       int res=QMessageBox::information(this,"提示","是否拍照",QMessageBox::Yes,QMessageBox::No);
       if(res)
       {
           QImage printscreen=this->image->toImage();
           QDateTime currentDateTime = QDateTime::currentDateTime();
           QString timeStr = currentDateTime.toString("yyyy-MM-dd-hh-mm-ss");

           //把路径从设置表里面拿出来
           this->model=this->con->getModel("device_info");
           Any ret=this->model->sqlSelect("select *from device_info;");
           Device* device=ret.cast_<Device*>();
           qDebug()<<device->getImagePath();
           QString fullFileName =device->getImagePath()+'/'+timeStr+".png";
           qDebug()<<"fullFileName="<<fullFileName;
           printscreen.save(fullFileName.toStdString().c_str());

           //计算图片大小
           QString imageFilePath =fullFileName;
           QFileInfo fileInfo(imageFilePath);
            double sizeInKB;
           if (fileInfo.exists())
           {
                   // 获取文件大小（单位：字节）
            qint64 fileSize = fileInfo.size();
            qDebug() << "图片文件大小（字节）：" << fileSize;

                   // 转换为更易读的单位（KB）
            sizeInKB = static_cast<double>(fileSize) / 1024;
            qDebug() << "图片文件大小（KB）：" << sizeInKB;
           }else
            {
            qDebug() << "图片文件不存在。";
            }


           //保存数据库
           qDebug()<<"id="<<id;
           this->model=this->con->getModel("Image_file");
           QString sql=QString("insert into image_files (user_id,image_path,image_name,image_size,image_time) values(%1,'%2','%3','%4','%5');")
                   .arg(id)
                   .arg(fullFileName.toStdString().c_str())
                   .arg(timeStr.toStdString().c_str())
                   .arg((int)sizeInKB)
                   .arg(timeStr.toStdString().c_str());
           qDebug()<<sql;
           this->model->sqlInstruct((char *)sql.toStdString().c_str());

       }


    }

        //现场拍照逻辑
}

void MainWidget::Clickplayback_button()
{
     HaveLogin(1);
     if(isLogin)
         emit ToVideoSelect();//录像回放逻辑
}

void MainWidget::Clickpictrue_button()
{
     HaveLogin(2);
     if(isLogin)
     emit ToScenepicture();//现场照片逻辑
}

void MainWidget::Clicklog_button()
{
    HaveLogin(3);
    if(isLogin)
        emit ToLog();
        //查看日志逻辑

}

void MainWidget::Clicktranscode_button()
{
     HaveLogin(4);
     if(isLogin)
         emit ToTransCode();//转码逻辑


}

void MainWidget::ClicklogIn_button()
{
    if(this->logIn_button->text()=="登录")
    {
        HaveLogin(6);
        //if(isLogin);//登录逻辑
    }
    else if(this->logIn_button->text()=="退出")
    {

        //把设置表中的设备名称拿出来？有没有其他方法，好像没有！！！


       this->model=this->con->getModel("device_info");
       Any ret=this->model->sqlSelect("select *from device_info;");
       Device* device=ret.cast_<Device*>();



       //退出逻辑日志写入，同时把刚刚录制的视频录制进数据库
       QDateTime currentDateTime = QDateTime::currentDateTime();
       qDebug()<<currentDateTime.toString();
       QString timeStr = currentDateTime.toString("yyyy-MM-dd-hh-mm-ss");
       this->model=this->con->getModel("operation_log");
       //日志写入

       QString sql= QString("insert into operation_log (user_id,operation_type,operation_time,log_device) values (%1,'%2','%3','%4');")
               .arg(id)
               .arg("退出")
               .arg(timeStr)
               .arg(device->getDeviceName());
         qDebug()<<sql;
        ret=this->model->sqlInstruct((char *)sql.toStdString().c_str());

        //视频录制进数据库
        this->model=this->con->getModel("video_file");
         sql=QString("insert into video_files (user_id,video_path,video_name,duration,video_img_path) VALUES (%1,'%2','%3','%4','%5');")
                .arg(id)
                .arg(this->getEncode()->getVideooutPath().toStdString().c_str())
                .arg(this->getEncode()->getVideooutName().toStdString().c_str())
                .arg(qCeil((qreal)this->getDecode()->getX()))
                .arg(this->getDecode()->getVideo_img_path().toStdString().c_str());
        qDebug()<<sql;

        this->model->insetVideoInfo((char *)sql.toStdString().c_str());
        //退出登录状态
        this->isLogin=false;
        this->getLogIn_button()->setText("登录");
    }

}

void MainWidget::WriteDateBaseVide()
{
    if(id)//登录就写进去，不登陆就不写
    {
        this->model=this->con->getModel("video_file");
         QString sql=QString("insert into video_files (user_id,video_path,video_name,duration,video_img_path) VALUES (%1,'%2','%3','%4','%5');")
                .arg(id)
                .arg(this->getEncode()->getVideooutPath().toStdString().c_str())
                .arg(this->getEncode()->getVideooutName().toStdString().c_str())
                .arg(qCeil((qreal)this->getDecode()->getX()))
                .arg(this->getDecode()->getVideo_img_path().toStdString().c_str());
        qDebug()<<sql;

        this->model->insetVideoInfo((char *)sql.toStdString().c_str());



    }

}








